package com.daocao.hua.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.InitAppBean;
import com.daocao.hua.api.bean.LoginBean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.event.V3LoginSuccessEvent;
import com.daocao.hua.model.InitAppModel;
import com.daocao.hua.util.MD5;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.PackageUtil;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.RBInfo;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3LoginByPassActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.btn_close)
    ImageView btnClose;
    @BindView(R.id.edit_pass)
    EditText editPass;
    @BindView(R.id.btn_see_pass)
    ImageView btnSeePass;
    @BindView(R.id.btn_forget)
    TextView btnForget;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private Unbinder unbinder;
    private boolean isChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_v3_login_by_pass);
        initBar();
        unbinder = ButterKnife.bind(this);
        txtTitle.setText("账号密码登录");
        setIsNeedCheckLogout(false);
    }

    private void getLogin(String account, String password) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        LoginBean bean = new LoginBean();
        bean.account = account;
        bean.password = MD5.getMD5str(password);
        Api.api_service.getLoginInfo(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "登录成功").show();
                    initApp();
                    UserGlobal.saveLoginInfo(result.getData());
                    Set<String> tagSet = new LinkedHashSet<String>();
                    // tagSet.add(model.getData().getUser_name());
                    tagSet.add(result.getData().getMobile());
                    JPushInterface.setAliasAndTags(getApplicationContext(), result.getData().getMobile() + "", tagSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            //  Log.i("", i + s + "       " + set.toString());
//                                ToastUtil.makeText(getApplicationContext(), i+"   "+s+"     "+set.toString(), Toast.LENGTH_SHORT).show();
                            switch (i) {
                                case 0:
//                                    Log.i("", i + s + "       " + set.toString());
                                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                                    PreferenceUtils.putBoolean(getApplicationContext(), "jPush_save_flag", true);
                                    break;
                                case 6002:
//                                    Log.i("6002", "60002");
                                    // 延迟 60 秒来调用 Handler 设置别名
                                    break;
                                default:
//                                    Log.i("6002", "default");
                            }
                        }

                    });

                });
    }

    public void initApp() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        InitAppBean bean = new InitAppBean();
        bean.client_type = Const.CLIENT_TYPE;
        bean.device_id = RBInfo.getInstance().getUniquePsuedoID();
        bean.user_agent = RBInfo.getInstance().getUserAgent();
        bean.os = Const.DevType.ANDROID;
        bean.os_version = RBInfo.getInstance().getOSVersion();

        bean.browser = "";
        bean.browser_version = "";
        bean.mobile_brand = RBInfo.getInstance().getBrand();
        bean.mobile_model = RBInfo.getInstance().getModel();
        bean.app_version = PackageUtil.getVersionName(this);
        double lat = PreferenceUtils.getDouble(getApplicationContext(), Const.KEY.LAT, -1);
        double lng = PreferenceUtils.getDouble(getApplicationContext(), Const.KEY.LNG, -1);
        if (lat > 0 && lng > 0) {
            bean.lat = lat;
            bean.lang = lng;
        }


        Api.api_service.getInitInfo(bean).compose(RxLifeUtil.NoErrorOn(this))

                .doOnError(throwable -> {

                    sendBroadcast();
                })
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends InitAppModel>>() {
                    @Override
                    public ObservableSource<? extends InitAppModel> apply(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        return Observable.empty();
                    }
                }).
                subscribe(result -> {
                    sendBroadcast();
                });
    }

    /**
     * 登录广播
     */
    private void sendBroadcast() {
        UserGlobal.login();
        EventBus.getDefault().post(new V3LoginSuccessEvent());

        if (!isSetGuesture()) {
            Dialog.showDefaultDialog(this, "", "您尚未绘制手势密码!", "取消", "去绘制", false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Util.startActivity(V3LoginByPassActivity.this, CreateGestureActivity.class);
                    finish();
                }

                @Override
                public void cancel() {
                    finish();
                }
            });
        } else {
            finish();
        }


    }


    private void init() {
    }

    private boolean checkPhone() {
        if (TextUtils.isEmpty(UI.toString(editPhone))) {
            ToastUtil.makeText(this, getResources().getString(R.string.phone_is_empty), 0).show();
            return false;
        }
        if (UI.toString(editPhone).length() < 11) {
            ToastUtil.makeText(this, getResources().getString(R.string.phone_is_error), 0).show();
            return false;
        }
        return true;
    }

    private boolean checkNewPwd() {
        if (TextUtils.isEmpty(UI.toString(editPass))) {
            ToastUtil.makeText(this, getResources().getString(R.string.password_is_empty), 0).show();
            return false;
        }
        return true;
    }

    @OnTextChanged({R.id.edit_phone, R.id.edit_pass})
    void afterTextChanged(Editable s) {
        if (UI.toString(editPhone).length() == 11 && !TextUtils.isEmpty(UI.toString(editPass))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        unbinder = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_close, R.id.btn_see_pass, R.id.btn_forget, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_close:
                editPhone.setText("");
                break;
            case R.id.btn_see_pass:
                isChecked = !isChecked;
                if (isChecked) {
                    //如果选中，显示密码
                    btnSeePass.setSelected(true);
                    editPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    btnSeePass.setSelected(false);
                    editPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.btn_forget:
                Util.startActivity(this, V3ForgetPassActivity.class);
                break;
            case R.id.btn_submit:
                if (checkPhone() && checkNewPwd()) {
                    getLogin(UI.toString(editPhone), UI.toString(editPass));
                }
                break;
        }
    }
}
